import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:flutter_kit_dsp/flutter_kit_dsp.dart';
import 'package:flutter_kit_plus/flutter_kit.dart';

import '../../tool/assets.dart';

class SoundItem extends StatefulWidget {
  final ChannelModel ch;
  const SoundItem({super.key, required this.ch});

  @override
  State<SoundItem> createState() => _SoundItemState();
}

class _SoundItemState extends State<SoundItem> {
  final textControler = TextEditingController();
  @override
  void initState() {
    super.initState();
    textControler.text = '';
    textControler.addListener(() {
      String text = textControler.text;
      // 自动添加前导0
      if (text.isNotEmpty && text[0] == '.') {
        textControler.text = '0$text';
        return;
      } else if (text.length > 1 && text[0] == '0' && text[1] != '.') {
        textControler.text = text.substring(1, text.length);
        return;
      }
    });
  }

  @override
  void dispose() {
    textControler.dispose();
    super.dispose();
  }

  List<Widget> getItem() {
    double iconHeight = widget.ch.num > 6
        ? 50
        : widget.ch.num < 3
            ? 20
            : 25;
    return [
      SizedBox(
        width: 40,
        height: 40,
        child: InkWell(
          onTap: () => globalController.beginDelayEdit(widget.ch),
          child: Center(child: Text('${widget.ch.num}', style: font40)),
        ),
      ),
      SizedBox(
        width: 50,
        height: 20,
        child: TextField(
          cursorHeight: 14,
          controller: textControler,
          style: const TextStyle(fontSize: 14, fontWeight: FontWeight.w600, color: Colors.black),
          textAlign: TextAlign.center,
          keyboardType: TextInputType.numberWithOptions(decimal: true), // 数字键盘（带小数点）
          ///边框
          decoration: const InputDecoration(
            contentPadding: EdgeInsets.symmetric(vertical: 0), // 调整上下内边距
            enabledBorder: OutlineInputBorder(
              // 默认边框
              borderSide: BorderSide(color: Colors.black, width: 1),
            ),
            focusedBorder: OutlineInputBorder(
                // 聚焦时边框
                // borderSide: BorderSide(color: Colors.red, width: 3),
                ),
            border: OutlineInputBorder(), // 让边框生效
          ),

          ///输入规则限制
          inputFormatters: [
            LengthLimitingTextInputFormatter(5), // 限制输入最大长度为3
            //FilteringTextInputFormatter.digitsOnly, // 只允许输入数字
            FilteringTextInputFormatter(
              RegExp(r'^\d*\.?\d*$'), // 允许数字和一个小数点
              allow: true,
            ),
          ],

          ///响应方法
          onTap: () => globalController.beginDelayEdit(widget.ch),
          onChanged: (value) => globalController.updateDelayEdit(widget.ch, value.float),
          onSubmitted: (value) {
            FocusScope.of(context).unfocus();
          },
          onEditingComplete: () {},
        ),
      ),
      InkWell(
          onTap: () => globalController.beginDelayEdit(widget.ch),
          child:
              Image.asset(widget.ch.isDelayEdit ? widget.ch.sound_img_select : widget.ch.sound_img, height: iconHeight))
    ];
  }

  @override
  Widget build(BuildContext context) {
    return LayoutBuilder(builder: (BuildContext context, BoxConstraints constraints) {
      bool isReversed = widget.ch.num % 2 == 0;
      textControler.text = globalController.autoDelay(widget.ch);
      return SizedBox(
        width: 60,
        height: constraints.maxHeight,
        child: Column(
            crossAxisAlignment: CrossAxisAlignment.center,
            mainAxisAlignment: isReversed ? MainAxisAlignment.spaceEvenly : MainAxisAlignment.spaceEvenly,
            children: isReversed ? getItem().reversed.toList() : getItem()),
      );
    });
  }
}
